import axios from 'axios'
import { ElLoading, ElNotification } from 'element-plus'
import { useAccountStore } from '@/store'
import type { AxiosInstance } from 'axios'
import type { ILyRequestConfig, IRealData } from '@/service/request/type'
import { ResultStatus } from '@/global/constant'

class LyRequest {
  instance: AxiosInstance

  constructor(config: ILyRequestConfig) {
    config.withCredentials = true
    // 1.创建axios新实例对象
    this.instance = axios.create(config)
    // 2.每个实例都有的拦截器
    this.instance.interceptors.request.use(
      (config) => {
        return config
      },
      (err) => {
        return Promise.reject(err)
      }
    )
    this.instance.interceptors.response.use(
      (res) => {
        return res
      },
      (err) => {
        return Promise.reject(err)
      }
    )
    // 3.某个实例才有的拦截器
    if (config.interceptors) {
      this.instance.interceptors.request.use(
        config.interceptors.requestSuccessFn,
        config.interceptors.requestFailureFn
      )
      this.instance.interceptors.response.use(
        config.interceptors.responseSuccessFn,
        config.interceptors.responseFailureFn
      )
    }
  }

  request(config: ILyRequestConfig) {
    // 某个请求的请求拦截
    if (config.interceptors?.requestSuccessFn) {
      config = config.interceptors.requestSuccessFn(config)
    }
    return new Promise<IRealData>((resolve) => {
      this.instance
        .request(config)
        .then((res: any) => {
          if (res.code !== ResultStatus.SUCCESS) return
          // 某个请求的响应拦截
          if (config.interceptors?.responseSuccessFn) {
            res = config.interceptors.responseSuccessFn(res)
          }
          // 有些请求开启提示信息
          config.isShowMsg &&
            ElNotification({
              type: 'success',
              message: res.msg,
              duration: 2500
            })
          resolve(res)
        })
        .catch((err) => {
          return Promise.reject(err)
        })
        .finally(() => {
          // 有些请求有loading效果
          config.isShowLoading && ElLoading.service().close()
          // 关闭登录按钮左边的加载圈
          useAccountStore().isLogining && (useAccountStore().isLogining = false)
        })
    })
  }

  get(config: ILyRequestConfig) {
    return this.request({ ...config, method: 'GET' })
  }

  post(config: ILyRequestConfig) {
    return this.request({ ...config, method: 'POST' })
  }

  put(config: ILyRequestConfig) {
    return this.request({ ...config, method: 'PUT' })
  }

  patch(config: ILyRequestConfig) {
    return this.request({ ...config, method: 'PATCH' })
  }

  delete(config: ILyRequestConfig) {
    return this.request({ ...config, method: 'DELETE' })
  }
}

export default LyRequest
